//
//  My_EInvitationViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/29.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"

#import "My_EInvitationListCell.h"
#import "TT_WebviewController.h"
#import "My_EInvitationViewController.h"

@interface My_EInvitationViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ZZLayoutDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger shareIndex;


@property (nonatomic, strong) NSMutableArray <CommonEinvitationModel *>*dataArray;

@end

@implementation My_EInvitationViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_MyInvitationList];
}

- (void)refreshParam {
    self.pageSize = 20;
    self.pageNum = 1;
}

- (void)initView {
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

#pragma mark Share
- (void)share {
    
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = self.dataArray[self.shareIndex].shareUrl;
    model.title = [NSString stringWithFormat:@"%@和%@的婚礼请柬",self.dataArray[self.shareIndex].brideName,self.dataArray[self.shareIndex].groomName];
    model.content = @"婚前婚后邀您体验";
    model.image = self.dataArray[self.shareIndex].invitationImage;
    [[TT_ShareManager share] callShareViewWithModel:model];
}

#pragma mark- 协议方法
//collectionView的协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader" forIndexPath:indexPath];
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    TT_WebviewController *vc = [[TT_WebviewController alloc] init];
    vc.webUrl = self.dataArray[indexPath.row].editUrl;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    My_EInvitationListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"My_EInvitationListCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    WEAKSELF
    cell.My_EInvitationListCellBlock = ^(My_EInvitationListCellActionType type) {
      
        weakSelf.shareIndex = indexPath.row;
        
        switch (type) {
            case My_EInvitationListCellActionType_share:{
                
                [weakSelf openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                    if (isLogin) {
                        [weakSelf share];
                    }
                }];
                
            } break;
            case My_EInvitationListCellActionType_del:{
                
            } break;
            default:
                break;
        }
        
    };
    
    return cell;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的高

    return 1.57*TTScreenWidth + 30;
}

- (NSInteger)layout:(ZZLayout *)layout columnNumberAtSection:(NSInteger)section {//每个区有几列

    return 1;
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距

    return CGFLOAT_MIN;
}

- (CGFloat)layout:(ZZLayout*)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距

    return CGFLOAT_MIN;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度

    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGFloat)layout:(ZZLayout*)layout spacingWithLastSectionForSectionAtIndex:(NSInteger)section {//本区区头和上个区区尾的间距
    return 0;
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {//设置不同分区的不同背景颜色
    return [UIColor whiteColor];
}


#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeVertical delegate:self];
        //打开区头悬浮功能(默认关闭)
        layout.sectionHeadersPinToVisibleBounds = NO;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColorHex(0xf1f1f1);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"My_EInvitationListCell" bundle:nil] forCellWithReuseIdentifier:@"My_EInvitationListCellID"];

        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];

        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;

        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        WEAKSELF
        _collectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_MyInvitationList];
        }];

        _collectionView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum++;
            [weakSelf request_MyInvitationList];

        }];
        
    }
    return _collectionView;
}

- (void)request_MyInvitationList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyInvitationList];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];

                if ([list isKindOfClass:[NSArray class]]) {
                    
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
                    }

                    for (int i = 0; i < list.count; i++) {
                        CommonEinvitationModel *model = [CommonEinvitationModel modelWithDictionary:list[i]];
                        
                        model.editUrl = [NSString
                                         stringWithFormat:@"%@?uiId=%@&userId=%@&isPersonal=1",model.invitationUrl,model.uiId,[TTUserModel sharedObject].userId];
                        model.shareUrl = [NSString
                                          stringWithFormat:@"%@?uiId=%@",model.invitationUrl,model.uiId];

                        [weakSelf.dataArray addObject:model];
                    }
                    
                    [weakSelf.collectionView reloadData];
                }

            } else {
//
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}

@end
